package pers.beic.springsecurity.config;


import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @auther Beic
 * @date 2022/3/30 18:04
 */
//开启webSecurity
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //没有权限未登录，则跳到登录页
        http.formLogin().loginPage("/goLogin").loginProcessingUrl("/toIndex").permitAll();
        //注销
        http.logout().logoutSuccessUrl("/");
        //记住我，cookie保留十四天，如果注销，自动删除cookie
        http.rememberMe();
        ;//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        http.csrf().disable();

    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("Beic").password(new BCryptPasswordEncoder().encode("ghb..123")).roles("vip1","vip2","vip3")
                .and().withUser("陈明东").password(new BCryptPasswordEncoder().encode("666")).roles("vip1");
    }
}
